package com.gzh.library

import android.app.NotificationManager
import android.content.Context
import android.os.Build
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import com.gzh.library.util.CfuConstant
import com.gzh.library.util.CfuPublicUtil

class UpdateChecker : Fragment() {
    private var mContext: FragmentActivity? = null

    companion object {
        private var isShow: Boolean = false     //是否弹窗
        private var apkPath: String = ""        //apk下载地址

        fun checkForDialog(fm: FragmentManager, isShowDialog: Boolean, path: String) {
            val content = fm.beginTransaction()
            val updateChecker = UpdateChecker()
            isShow = isShowDialog
            apkPath = path
            content.add(updateChecker, null).commitAllowingStateLoss()
        }
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mContext = context as FragmentActivity
        /**
         * 8.0通知渠道
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CfuPublicUtil.createNotificationChannel(
                context = mContext,
                channelId = "cfu_download",
                channelName = "版本更新",
                channelDescription = "版本更新下载新版APP时的进度通知",
                importance = NotificationManager.IMPORTANCE_DEFAULT
            )
        }
        checkForUpdates()
    }

    /**
     * 检测更新
     */
    private fun checkForUpdates() {
        if (isShow) {
            activity?.let { it1 ->
                // 如果下载服务正在运行则不再弹出提示框
                if (!CfuPublicUtil.isServiceRunning(
                        it1,
                        "com.gzh.checkforupdate.DownloadService"
                    )
                ) {
                    showDialog(apkPath)
                }
            }
        }
    }

    /**
     * 显示更新提示框
     */
    private fun showDialog(apkUrl: String) {
        val d = UpdateDialog()
        val args = Bundle()
        args.putString(CfuConstant.APK_DOWNLOAD_URL, apkUrl)
        d.arguments = args
        mContext?.supportFragmentManager?.let { d.show(it, null) }
    }
}